package other.process;

import ch.qos.logback.core.joran.action.ActionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.geotools.geojson.GeoJSON;
import utilityTools.GeoJsonUtiles;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author jlj
 * @Date 2022-04-11 16:49
 * @Description 读取Json文件内容
 * @Modified
 */
public class ReadJson {

    public void readJson(String fileName,String pathSource) throws Exception {
        JSONObject jsonSource = GeoJsonUtiles.getGeoJsonSource(new File(pathSource));
        JSONArray resultArray = jsonSource.getJSONArray("Results");//只有一个结果
        List<IssueBug> response=new ArrayList<>();
        for (int idxResult = 0; idxResult < resultArray.size(); idxResult++) {
            JSONObject obj1 = resultArray.getJSONObject(idxResult);
            JSONArray vulnerabilities = obj1.getJSONArray("Vulnerabilities");
            System.out.println("Vulnerabilities的原始数量："+vulnerabilities.size());
            for (int idx = 0; idx < vulnerabilities.size(); idx++) {
                JSONObject perIssue = vulnerabilities.getJSONObject(idx);
                String pkgName = perIssue.getString("PkgName");
                String vulnerabilityID = perIssue.getString("VulnerabilityID");
                IssueBug iss = new IssueBug()
                        .setIndex(idx+1)
                        .setPkgName(pkgName)
                        .setIssueID(vulnerabilityID);
                response.add(iss);
            }
        }
        System.out.println(fileName+"中bug的数量："+response.size());
        this.exportGroupPeopleList(fileName,response);
        //for (Map.Entry<Integer, IssueBug> perIss : response.entrySet()) {
        //    System.out.println(perIss.getValue().getPkgName() + ":" + perIss.getValue().getIssueID());
        //}
    }

    public void exportGroupPeopleList(String fileName,List<IssueBug> list) throws Exception{
        //构造表头（不能使用中文表头，否则乱码）
        StringBuilder sb = new StringBuilder("PkgName,VulnerabilityID\r");
        for(IssueBug perIssue:list){
            sb.append(perIssue.getPkgName()).append(",").append(perIssue.getIssueID()).append("\r");
        }
        String filename = "C:\\Users\\Lenovo\\Desktop\\IssueOut\\"+fileName+".csv";
        //使用try-catch统一管理资源
        try (FileWriter fw = new FileWriter(filename);
             BufferedWriter writer = new BufferedWriter(fw)) {
            writer.write(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("出现错误，操作失败");
        }
    }
}
